package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.dao.OrderSettingDao;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    @Transactional
    public void add(List<OrderSetting> orderSettingList) throws SunnydayException {
        //1.遍历List<OrderSetting>
        for (OrderSetting os : orderSettingList) {
            //2.通过时间查询预约设置信息表，是否存在要插入的日期
            OrderSetting osInDb = orderSettingDao.findByOrderData(os.getOrderDate());
            //3.判断有没有这个实体
            if (null!=osInDb){
                //3.1存在该日期,如果已预约数量大于你要插入的可预约数量
                if(osInDb.getReservations()>os.getNumber()){
                    //就抛异常
                    throw new SunnydayException(os.getOrderDate()+"中：可预约人数不能小于已预约人数");
                }else {
                    //数据合理，更新可预约人数，日期还是那个日期
                    orderSettingDao.updateNumber(os);
                }
            }else {
                //4.如果没有这个实体，代表表中都没有这个日期
                orderSettingDao.add(os);
            }
        }
    }

    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String month) {
        //已经拿到了"2021-05"
        //拼接每个月的起始日期
        String startDate = month+"-01";//2021-05-01"
        return orderSettingDao.getOrderSettingByMonth(startDate);
    }

    /**
     *
     */
    @Override
    public void editNumberByDate(OrderSetting os) {
        //2.通过时间查询预约设置信息表，是否存在要插入的日期
        OrderSetting osInDb = orderSettingDao.findByOrderData(os.getOrderDate());
        //3.判断有没有这个实体
        if (null!=osInDb){
            //3.1存在该日期,如果已预约数量大于你要插入的可预约数量
            if(osInDb.getReservations()>os.getNumber()){
                //就抛异常
                throw new SunnydayException(os.getOrderDate()+"中：可预约人数不能小于已预约人数");
            }else {
                //数据合理，更新可预约人数，日期还是那个日期
                orderSettingDao.updateNumber(os);
            }
        }
    }
}
